package com.vehicle.stock.provider.rocketmq.producer;

import com.vehicle.common.util.Jsons;
import com.vehicle.stock.api.entity.Seckill;
import com.vehicle.stock.api.entity.SuccessKilled;
import com.vehicle.stock.api.service.SeckillService;
import org.apache.rocketmq.client.producer.LocalTransactionExecuter;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by yantingbin on 2017/8/11.
 */
@Component
public class TransactionExecuterImpl implements LocalTransactionExecuter {
    private static final Logger LOGGER= LoggerFactory.getLogger(TransactionExecuterImpl.class);
    @Autowired
    private SeckillService seckillService;

    @Override
    public LocalTransactionState executeLocalTransactionBranch(Message msg, Object arg) {
        String str= new String(msg.getBody());
        SuccessKilled successKilled= Jsons.fromJson(str, SuccessKilled.class);
        try{
           boolean result= seckillService.executeSeckill(successKilled.getSeckillId(),successKilled.getUserPhone());

           if(result){
               return LocalTransactionState.COMMIT_MESSAGE;
           }
        }catch (Exception e){
            LOGGER.error("executeseckill error ",e);
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }

        return LocalTransactionState.UNKNOW;
    }
}
